package com.ajx.blog.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author: Mr.Li
 * @date: 2022/4/12 22:22
 * @description:
 */
@Component
public class ChatAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private Logger logger = LoggerFactory.getLogger(ChatAuthenticationFailureHandler.class);
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String message = e.getMessage();
        HashMap<String, Object> returnMap = new HashMap<>();
        ServletOutputStream out = httpServletResponse.getOutputStream();

        httpServletResponse.setContentType("application/json;charset=UTF-8");

        if (e instanceof LockedException){
            returnMap.put("code",1);
            returnMap.put("data", null);
            returnMap.put("msg", "账户被锁定");


        }else if (e instanceof CredentialsExpiredException){
            returnMap.put("code",1);
            returnMap.put("data", null);
            returnMap.put("msg", "密码过期");
        }else if (e instanceof AccountExpiredException){
            returnMap.put("code",1);
            returnMap.put("data", null);
            returnMap.put("msg", "账户过期");

        }else if (e instanceof BadCredentialsException){
            returnMap.put("code",1);
            returnMap.put("data", null);
            returnMap.put("msg", "密码错误");

        }else if(e instanceof InternalAuthenticationServiceException){
            returnMap.put("code",1);
            returnMap.put("data", null);
            returnMap.put("msg", "账号不存在");

        }
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(out, returnMap);
        out.flush();
        out.close();


    }
}
